/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.escom.listener.recursos;

import com.escom.admin.xml.XMLReference;
import java.io.InputStream;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Web application lifecycle listener.
 * @author yamil
 */

public class ApplicationContext implements ServletContextListener {

   protected  static ClassPathXmlApplicationContext appContext;
   protected  static BeanFactory factory;
   private static boolean log4jInitialized = false;
   private static Logger logger = Logger.getLogger(ApplicationContext.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println("iniciliazando todo");
       // initializeLog4j();
        getinicializarSpring(sce);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    private  void getinicializarSpring(ServletContextEvent e){

        String ruta=null;
      
       ruta="applicationContext.xml";
       if (!log4jInitialized) {
  	log4jInitialized = true;
        System.out.println("******************************+Real PATH:***********************************");                      appContext  = new ClassPathXmlApplicationContext(ruta);
         factory = (BeanFactory) appContext;
        System.out.println("*****************++Salio chido todo****************************************");
        }

    }
    public static Object getBean(String nameBean){
        return factory.getBean(nameBean);
    }

    public synchronized void initializeLog4j() {
		try {
			if (!log4jInitialized) {
				log4jInitialized = true;
				InputStream log4jConfigStream = XMLReference.class.getResourceAsStream("log4j.configure.xml");
				DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				Document log4jDocument = docBuilder.parse(log4jConfigStream);
				DOMConfigurator.configure((Element) log4jDocument.getFirstChild());
			}
		} catch (Exception e) {
			logger.debug("No es posible configurar el log: "  +e.getMessage());
			e.printStackTrace();
		}
	}
}
